package com.atguigu.gulimall.seckill.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRegisterVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SeckillSkuRelationVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private final String SESSION_CACHE_PREFIX = "seckill:session:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void uploadSeckillShuLatest3Days() {

        R r = couponFeignService.getLastest3DaySession();
        if (r.getCode() == 0) {
            //上架商品
            List<SeckillSessionsWithSkus> sessions = r.getDate(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //保存到Redis中
            //保存活动信息
            saveSessionInfos(sessions);
            //保存活动的关联商品信息
            saveSessionSkuInfos(sessions);
        }
    }

    /**
     * 获取当前上架的秒杀商品信息
     **/
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1:确定当前时间属于哪个秒杀场次
        Long now = System.currentTimeMillis();
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSION_CACHE_PREFIX, "");
            String[] split = replace.split("_");
            Long start = Long.parseLong(split[0]);
            Long end = Long.parseLong(split[1]);
            if (now >= start && now <= end) {
                //2:获取这个场次需要的所有商品
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = ops.multiGet(range);
                if (CollectionUtils.isNotEmpty(list)) {
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        SeckillSkuRedisTo redisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                        //TODO 判断当前时间是否处于秒杀阶段,要是不是,就不能返回商品的随机码
                        //处理随机码
                        Long startTime = redisTo.getStartTime();
                        Long endTime = redisTo.getEndTime();
                        if (now >= startTime && now <= endTime) {
                        } else {
                            redisTo.setRandomCode(null);
                        }
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    /**
     * 获取参与秒杀商品的所有SKU信息
     **/
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        Set<String> keys = hashOps.keys();
        if (CollectionUtils.isNotEmpty(keys)) {
            String regx = "//d" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSONObject.parseObject(json, SeckillSkuRedisTo.class);

                    //处理随机码
                    long now = System.currentTimeMillis();
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    if (now >= startTime && now <= endTime) {
                    } else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    /**
     * 创建秒杀
     **/
    @Override
    public String kill(Long killId, String key, Integer num) {
        MemberRegisterVo registerVo = LoginUserInterceptor.loginUser.get();

        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = ops.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            //成功的逻辑
            SeckillSkuRedisTo redis = JSONObject.parseObject(json, SeckillSkuRedisTo.class);
            //校验合法性
            //1:是否在合法时间内
            long time = System.currentTimeMillis();
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            if (time >= startTime && time <= endTime) {
                //检验随机码和商品ID
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    //3:验证购物车数量是否合理
                    if (num <= redis.getSeckillLimit()) {
                        //验证这个人是否已经购买过,幂等性,只要秒杀成功,就去站位:userId_SessionId_promotionId,占位数据也有自动过期时间(就是秒杀结束时间)
                        String redisKey = registerVo.getId() + "_" + key;
                        Long ttl = endTime - startTime;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MICROSECONDS);
                        if (aBoolean) {
                            //如果占位成功,就说明从来没有买过这场的秒杀商品,扣减Redis信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                //秒杀成功,快速下单,发送MQ消息
                                //生成订单号,设置秒杀的相关信息
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setMemberId(registerVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                orderTo.setSkuId(redis.getSkuId());
                                orderTo.setSeckillPrice(redis.getSeckillPrice());
                                orderTo.setOrderSn(timeId);
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                                return timeId;
                            }
                        } else {
                            //说明已经购买过了
                            return null;
                        }
                    }
                }
            } else {
                return null;
            }
        }

        return null;
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions) {
        sessions.stream().forEach(session -> {
            long start = session.getStartTime().getTime();
            long end = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + start + "_" + end;

            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = session.getRelationEntities().stream().map(item -> item.getPromotionId() + "_" + item.getSkuId()).collect(Collectors.toList());
                //保存活动信息
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions) {
        sessions.stream().forEach(seckillSessionsWithSkus -> {
            //准备hash操作
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            seckillSessionsWithSkus.getRelationEntities().stream().forEach(seckillSkuRelationVo -> {

                String token = UUID.randomUUID().toString().replace("-", "");
                if (!hashOps.hasKey(seckillSkuRelationVo.getPromotionId() + "_" + seckillSkuRelationVo.getSkuId())) {
                    //缓存商品
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1:sku的基本数据
                    R r = productFeignService.info(seckillSkuRelationVo.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo skuInfo = r.getDate("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(skuInfo);
                    }

                    //2:sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuRelationVo, redisTo);
                    //3:设置当前商品的秒杀时间信息
                    redisTo.setStartTime(seckillSessionsWithSkus.getStartTime().getTime());
                    redisTo.setEndTime(seckillSessionsWithSkus.getEndTime().getTime());
                    //4:设置秒杀商品的随机码
                    redisTo.setRandomCode(token);
                    String string = JSON.toJSONString(redisTo);
                    hashOps.put(seckillSkuRelationVo.getPromotionId() + "_" + seckillSkuRelationVo.getSkuId(), string);

                    //引入分布式的信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //5:使用库存作为商品秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuRelationVo.getSeckillCount());
                }
            });
        });
    }
}
